export interface DnsRecord {
    type: string;
    name: string;
    value: string;
    ttl?: number;
}

export interface WhoisInfo {
    domain?: string;
    registrar?: string;
    creationDate?: string;
    expirationDate?: string;
    updatedDate?: string;
    status?: string[];
    nameServers?: string[];
}

export interface DomainInfo {
    domain: string;
    ipAddresses: string[];
    dnsRecords: DnsRecord[];
    whoisInfo?: WhoisInfo;
}

// DNS查询服务 - 使用国内DNS服务器
const DNS_SERVICES = [
    {
        name: 'aliyun',
        url: (domain: string, type: string) => `https://dns.alidns.com/resolve?name=${domain}&type=${type}`,
    },
    {
        name: 'dnspod',
        url: (domain: string, type: string) => `https://doh.pub/dns-query?name=${domain}&type=${type}`,
    },
    {
        name: '114dns',
        url: (domain: string, type: string) => `https://dns.114dns.com/dns-query?name=${domain}&type=${type}`,
    }
];

// 验证域名格式
export function isValidDomain(domain: string): boolean {
    const domainRegex = /^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
    return domainRegex.test(domain) && domain.length > 0 && domain.length <= 253;
}

// 清理域名输入
export function cleanDomain(domain: string): string {
    return domain.toLowerCase().replace(/^https?:\/\//, '').replace(/\/.*$/, '');
}

// 单个DNS记录查询函数
async function queryDnsRecord(domain: string, type: string, service: any): Promise<DnsRecord[]> {
    try {
        const url = service.url(domain, type);
        const response = await fetch(url, {
            headers: {
                'Accept': 'application/dns-json',
            },
            // 添加超时控制
            signal: AbortSignal.timeout(5000), // 5秒超时
        });

        if (!response.ok) return [];

        const data = await response.json();
        if (!data.Answer) return [];

        return data.Answer.map((answer: any) => ({
            type,
            name: answer.name,
            value: answer.data,
            ttl: answer.TTL,
        }));
    } catch (error) {
        console.warn(`Failed to fetch ${type} records from ${service.name} for ${domain}:`, error);
        return [];
    }
}

// 获取DNS记录 - 优化版本，并行查询
async function getDnsRecords(domain: string): Promise<DnsRecord[]> {
    const recordTypes = ['A', 'AAAA', 'CNAME', 'MX', 'TXT', 'NS', 'SOA'];
    const allRecords: DnsRecord[] = [];

    // 为每种记录类型并行查询所有DNS服务器
    const recordPromises = recordTypes.map(async (type) => {
        const typeRecords: DnsRecord[] = [];

        // 并行查询所有DNS服务器
        const serverPromises = DNS_SERVICES.map(service =>
            queryDnsRecord(domain, type, service)
        );

        // 等待第一个成功的响应
        const results = await Promise.allSettled(serverPromises);

        // 收集所有成功的记录
        for (const result of results) {
            if (result.status === 'fulfilled' && result.value.length > 0) {
                typeRecords.push(...result.value);
                break; // 一旦有结果就停止，避免重复
            }
        }

        return typeRecords;
    });

    // 等待所有记录类型完成
    const allTypeResults = await Promise.all(recordPromises);

    // 合并所有记录
    for (const records of allTypeResults) {
        allRecords.push(...records);
    }

    return allRecords;
}

// 获取WHOIS信息 - 添加超时控制
async function getWhoisInfo(domain: string): Promise<WhoisInfo | null> {
    try {
        const response = await fetch(`https://whois.whoisxmlapi.com/api/v1?apiKey=demo&domainName=${domain}`, {
            signal: AbortSignal.timeout(8000), // 8秒超时
        });

        if (!response.ok) return null;

        const data = await response.json();
        return {
            domain: data.domainName,
            registrar: data.registrar?.name,
            creationDate: data.creationDate,
            expirationDate: data.expirationDate,
            updatedDate: data.updatedDate,
            status: data.status,
            nameServers: data.nameServers,
        };
    } catch (error) {
        console.warn('Failed to fetch WHOIS info:', error);
        return null;
    }
}

// 主函数：解析域名 - 默认只获取A记录
export async function resolveDomain(domain: string): Promise<DomainInfo | null> {
    const cleanDomainName = cleanDomain(domain);

    if (!isValidDomain(cleanDomainName)) {
        throw new Error('无效的域名格式');
    }

    try {
        // 只获取A记录和WHOIS信息
        const [aRecords, whoisInfo] = await Promise.allSettled([
            getSpecificDnsRecord(cleanDomainName, 'A'),
            getWhoisInfo(cleanDomainName),
        ]);

        // 提取IP地址
        const ipAddresses = aRecords.status === 'fulfilled'
            ? aRecords.value
                .map(record => record.value)
                .filter(value => {
                    // 确保是有效的IPv4地址
                    const ipRegex = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
                    const match = value.match(ipRegex);
                    if (!match) return false;

                    // 检查每个段是否在0-255范围内
                    for (let i = 1; i <= 4; i++) {
                        const segment = parseInt(match[i]);
                        if (segment < 0 || segment > 255) return false;
                    }
                    return true;
                })
            : [];

        return {
            domain: cleanDomainName,
            ipAddresses,
            dnsRecords: aRecords.status === 'fulfilled' ? aRecords.value : [],
            whoisInfo: whoisInfo.status === 'fulfilled' ? whoisInfo.value || undefined : undefined,
        };
    } catch (error) {
        console.error('Domain resolution failed:', error);
        throw error;
    }
}

// 获取指定类型的DNS记录
export async function getDnsRecordByType(domain: string, type: string): Promise<DnsRecord[]> {
    const cleanDomainName = cleanDomain(domain);

    if (!isValidDomain(cleanDomainName)) {
        throw new Error('无效的域名格式');
    }

    return await getSpecificDnsRecord(cleanDomainName, type);
}

// 获取特定类型的DNS记录 - 优化版本
export async function getSpecificDnsRecord(domain: string, type: string): Promise<DnsRecord[]> {
    // 并行查询所有DNS服务器
    const serverPromises = DNS_SERVICES.map(service =>
        queryDnsRecord(domain, type, service)
    );

    const results = await Promise.allSettled(serverPromises);

    // 返回第一个成功的结果
    for (const result of results) {
        if (result.status === 'fulfilled' && result.value.length > 0) {
            return result.value;
        }
    }

    console.warn(`Failed to fetch ${type} records from all DNS servers for ${domain}`);
    return [];
} 